<template>
  <div class="tab-base-info">
    <div class="container">
      <template v-for="(mainItem, mainIndex) in list">
        <section
          v-if="mainItem.fieldList.length > 0"
          :key="mainIndex"
          class="section">
          <flexbox class="section-title">
            <span class="icon" />
            <span class="text">
              {{ mainItem.name }}
            </span>
          </flexbox>
          <flexbox
            :gutter="0"
            align="stretch"
            wrap="wrap"
            style="padding: 10px 8px 0;"
            class="section-body">
            <flexbox-item
              v-for="(item, index) in mainItem.fieldList"
              :span="getShowBlock(item.formType) ? 12 : 0.5"
              :key="index"
              class="section-content">
              <div
                v-if="item.formType === 'pic'"
                class="content">
                <div class="content-name">{{ item.name }}</div>
                <div class="content-value img-content">
                  <template v-if="isArrayFn(item.value)">
                    <img
                      v-src="img.url"
                      v-for="(img, index) in item.value"
                      :key="img.url"
                      alt=""
                      class="img-cell"
                      @click="previewImage(index, item.value)">
                  </template>
                  <template v-else-if="item.value">
                    <img
                      v-src="item.value.url || ''"
                      alt=""
                      class="img-cell"
                      @click="previewImage(0, [item.value])">
                  </template>
                </div>
              </div>
              <div
                v-else-if="item.formType === 'file'"
                class="content">
                <div class="content-name">{{ item.name }}</div>
                <div class="content-value file-content">
                  <wk-file-cell
                    v-for="(file, fileIndex) in item.value"
                    :key="fileIndex"
                    :data="file"
                    :list="item.value"
                    :index="fileIndex" />
                </div>
              </div>

              <!--<flexbox
                v-else-if="item.formType === 'map_address'"
                :gutter="0"
                wrap="wrap">
                <flexbox-item
                  :span="0.5"
                  class="b-cell"
                  @click.native="checkMapView(item)">
                  <flexbox
                    class="content"
                    align="stretch">
                    <div class="content-name">定位</div>
                    <div
                      class="content-value"
                      style="color: #3E84E9;cursor: pointer;">{{ item.value.location }}</div>
                  </flexbox>
                </flexbox-item>
                <flexbox-item
                  :span="0.5"
                  class="content">
                  <flexbox
                    class="b-cell-b"
                    align="stretch">
                    <div class="content-name">区域</div>
                    <div class="content-value">{{ item.value.address }}</div>
                  </flexbox>
                </flexbox-item>
                <flexbox-item
                  :span="0.5"
                  class="content">
                  <flexbox
                    class="content"
                    align="stretch">
                    <div class="content-name">详细地址</div>
                    <div class="content-value">{{ item.value.detailAddress }}</div>
                  </flexbox>
                </flexbox-item>
              </flexbox>-->

              <flexbox
                v-else
                align="stretch"
                class="content">
                <div class="content-name">{{ item.name }}</div>
                <div
                  :class="{ 'can-visit--underline': canVisit(item) }"
                  class="content-value"
                  @click="handleShowDetail(item)">{{ formatValue(item) }}</div>
              </flexbox>

            </flexbox-item>
          </flexbox>
        </section>
      </template>
    </div>

    <map-view
      v-if="showMapView"
      :title="mapViewInfo.title"
      :lat="mapViewInfo.lat"
      :lng="mapViewInfo.lng"
      @hidden="showMapView=false" />

    <!-- CRM详情页面 -->
    <c-r-m-full-screen-detail
      :visible.sync="showDetail"
      :id="rowId"
      :crm-type="detailType"
      @handle="showDetail = false" />

    <j-x-c-full-screen-detail
      v-if="showDetail && rowId && detailType && detailType !== 'customer'"
      :id="rowId"
      :type="detailType"
      @update="handleRefresh"
      @close="showDetail = false" />
  </div>
</template>

<script>
import { jxcFieldDetailInformationAPI } from '@/api/jxc/field'
import { isArray, isEmpty, isObject } from '@/utils/types'
import jxcTypes from '../../jxcTypes'

import MapView from '@/components/MapView' // 地图详情
import WkFileCell from '@/components/NewCom/WkFile/Cell'
import { separator } from '@/filters/vueNumeralFilter/filters'

// 基本信息
export default {
  name: 'TabBaseInfo',
  components: {
    MapView,
    WkFileCell,
    CRMFullScreenDetail: () => import('@/components/CRMFullScreenDetail'),
    JXCFullScreenDetail: () => import('../../components/JXCFullScreenDetail')
  },
  inheritAttrs: false,
  props: {
    id: {
      type: [String, Number],
      required: true
    },
    label: {
      type: [String, Number],
      required: true
    },
    detailData: {
      type: Object
    }
  },
  data() {
    return {
      list: [],
      causeArr: [
        'supplier_cause',
        'purchase_cause',
        'warehouse_cause',
        'salereturn_cause',
        'sale_cause',
        'retreat_cause',
        'customer'
      ],

      mapViewInfo: null,
      showMapView: false,

      rowId: null,
      detailType: null,
      showDetail: false
    }
  },
  computed: {
    params() {
      return {
        label: this.label,
        id: this.id,
        detailData: this.detailData
      }
    }
  },
  watch: {
    params: {
      handler() {
        if (!isEmpty(this.detailData)) {
          this.getInformation()
        }
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    isArrayFn(val) {
      return isArray(val)
    },

    previewImage(index, list) {
      this.$bus.emit('preview-image-bus', {
        index: index,
        data: list
      })
    },

    getInformation() {
      this.loading = true
      jxcFieldDetailInformationAPI({
        label: this.label,
        id: this.id
      }).then(res => {
        this.loading = false
        // console.log('information', res.data)
        let findIndex = -1
        let formType = 'text'
        let objFormType = 'text'
        if ([
          jxcTypes.jxc_collection.label,
          jxcTypes.jxc_payment.label
        ].includes(this.label)) {
          const fieldName = this.label === jxcTypes.jxc_collection.label ? 'collectionType' : 'paymentType'
          findIndex = res.data.findIndex(o => o.fieldName === fieldName)
          if (findIndex !== -1) {
            switch (res.data[findIndex].value) {
              case '采购退货':
                formType = 'retreat_cause'
                objFormType = 'supplier_cause'
                break
              case '销售':
                formType = 'sale_cause'
                objFormType = 'customer'
                break
              case '采购':
                formType = 'purchase_cause'
                objFormType = 'supplier_cause'
                break
              case '销售退货':
                formType = 'salereturn_cause'
                objFormType = 'customer'
                break
            }
            findIndex = res.data.findIndex(o => o.fieldName === 'relatedId')
            if (findIndex !== -1) {
              res.data[findIndex].formType = formType
            }
            findIndex = res.data.findIndex(o => o.fieldName === 'collectionObject')
            if (findIndex !== -1) {
              res.data[findIndex].formType = objFormType
            }
          }
        }
        this.formatFields(res.data)
      }).catch(() => {
        this.loading = false
      })
    },

    /**
     * 格式化字段
     * @param data
     */
    formatFields(data) {
      const baseList = []
      const sysList = []
      const picList = []

      data.forEach(item => {
        if (item.formType === 'pic') {
          picList.push(item)
        } else if (item.sysInformation == 0) {
          baseList.push(item)
        } else if (item.sysInformation == 1) {
          sysList.push(item)
        }
      })

      this.list = [
        {
          name: '基本信息',
          type: 0,
          fieldList: baseList
        },
        {
          name: '系统信息',
          type: 1,
          fieldList: sysList
        }
      ]
      if (picList.length > 0) {
        this.list.push({
          name: '图片信息',
          type: 2,
          fieldList: picList
        })
      }
      if (this.label === jxcTypes.jxc_sale.label) {
        const list = [
          {
            formType: 'text',
            fieldName: 'contacts',
            name: '联系人',
            value: this.detailData.contacts
          },
          {
            formType: 'text',
            fieldName: 'telephone',
            name: '电话',
            value: this.detailData.telephone
          },
          {
            formType: 'text',
            fieldName: 'detailAddress',
            name: '地址',
            value: this.detailData.detailAddress
          }
        ]
        this.list.splice(1, 0, {
          name: '收货信息',
          type: 3,
          fieldList: list
        })
      }
    },

    /**
     * 格式化字段值
     */
    formatValue(item) {
      if (isEmpty(item.value)) return ''
      if (isObject(item.value)) {
        return item.value.hasOwnProperty('name') ? item.value.name : item.value
      }
      if (isArray(item.value)) {
        return item.value.join(',')
      }
      if (item.formType === 'floatnumber') {
        return separator(item.value || 0)
      }
      return item.value
    },

    /**
     * 是否可点击
     */
    canVisit(item) {
      if (item.formType === 'warehouse_cause') return false
      return this.causeArr.includes(item.formType)
    },

    getShowBlock(type) {
      return ['map_address', 'file', 'pic'].includes(type)
    },

    /**
     * 查看地图详情
     */
    checkMapView(item) {
      if (item.value && item.value !== '') {
        this.mapViewInfo = {
          title: item.value.location,
          lat: item.value.lat,
          lng: item.value.lng
        }
        this.showMapView = true
      }
    },

    /**
     * 刷新
     */
    handleRefresh() {
      this.getInformation()
    },

    handleShowDetail(item) {
      if (!this.canVisit(item)) return
      console.log('obj field: ', item)
      this.rowId = item.value.id || null
      this.detailType = null
      const map = {
        supplier_cause: 'jxc_supplier',
        purchase_cause: 'jxc_purchase',
        salereturn_cause: 'jxc_salereturn',
        sale_cause: 'jxc_sale',
        retreat_cause: 'jxc_retreat',
        customer: 'customer'
      }
      if (map.hasOwnProperty(item.formType)) {
        this.detailType = map[item.formType]
        this.showDetail = true
      }
    }
  }
}
</script>

<style scoped lang="scss">
.tab-base-info {
  position: relative;
  width: 100%;
  height: 100%;
  padding: 15px;
  overflow: auto;
  .section {
    margin-top: 25px;
    &:first-child {
      margin-top: 0;
    }

    .section-title {
      font-size: 14px;
      font-weight: 600;
      padding: 5px 15px;

      .icon {
        width: 4px;
        height: 14px;
        border-radius: 2px;
        background-color: $xr-color-primary;
      }
      .text {
        vertical-align: middle;
        margin-left: 8px;
      }
    }
    .section-body {
      padding: 10px 8px 0;

      .section-content {
        width: auto;
        padding: 8px;

        .content {
          padding: 0 10px;
          .content-name {
            width: 100px;
            font-size: 13px;
            flex-shrink: 0;
            color: #777;
            margin-right: 10px;
          }
          .content-value {
            font-size: 13px;
            color: #333;
            line-height: 1.2;
            white-space: pre-wrap;
            word-wrap: break-word;
            word-break: break-all;
          }
        }

        .img-content {
          width: 100%;
          display: flex;
          align-items: center;
          flex-wrap: wrap;
          .img-cell {
            max-width: 100px;
            border-radius: 4px;
            cursor: pointer;
            margin-top: 15px;
            &:not(:first-child) {
              margin-left: 20px;
            }
          }
        }

        .file-content {
          width: 70%;
          padding-top: 15px;
        }

      }
    }
  }
}
</style>
